package org.csu.linkgame.controller;

import de.felixroske.jfxsupport.FXMLController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.csu.linkgame.domain.GameHistory;
import org.csu.linkgame.domain.User;
import org.csu.linkgame.service.ClassForDoubleGame.*;
import org.csu.linkgame.service.ClassForGame.testView;

import java.net.URL;
import java.sql.*;
import java.util.Comparator;
import java.util.ResourceBundle;

@FXMLController
public class DoubleViewController implements Initializable {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/super_link?useUnicode=true&characterEncoding=utf8";


    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "2003052288mjp";
    @FXML
    public Button startButton;
    @FXML
    public Button prepareButton;
    @FXML
    public Button cancelPrepareButton;
    @FXML
    public AnchorPane gameWindow;
    User user;
    dgServiceImpl dgCanvas;
    @FXML
    public ImageView userInfo;
    @FXML
    public ImageView enemyInfo;
    @FXML
    public TableView myHistory;
    @FXML
    public TableView enemyHistory;
    @FXML
    public TableColumn myTime;
    @FXML
    public TableColumn myWinner;
    @FXML
    public TableColumn myLoser;
    @FXML
    public TableColumn enemyTime;
    @FXML
    public TableColumn enemyWinner;
    @FXML
    public TableColumn enemyLoser;
    final ObservableList<GameHistory> data = FXCollections.observableArrayList();
    final ObservableList<GameHistory> enemyData = FXCollections.observableArrayList();
    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }
    public void setDgCanvas(dgServiceImpl dgCanvas){
        this.dgCanvas = dgCanvas;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public void setUserInfoImage() throws Exception{
        Image image = new Image("http://orange-1312206514.cos.ap-guangzhou.myqcloud.com/images/dg"+user.getUsername()+".jpg", 487,
                207, true, true);
        userInfo.setImage(image);
        Image image2 = new Image("http://orange-1312206514.cos.ap-guangzhou.myqcloud.com/images/dg"+userGameView.enemy.getUsername()+".jpg", 487,
                207, true, true);
        enemyInfo.setImage(image2);
        // 进行数据绑定
        myTime.setCellValueFactory(
                new PropertyValueFactory<GameHistory,String>("endTime")
        );
        myWinner.setCellValueFactory(
                new PropertyValueFactory<GameHistory,String>("winner")
        );
        myLoser.setCellValueFactory(
                new PropertyValueFactory<GameHistory,String>("loser")
        );
        // 进行数据绑定
        enemyTime.setCellValueFactory(
                new PropertyValueFactory<GameHistory,String>("endTime")
        );
        enemyWinner.setCellValueFactory(
                new PropertyValueFactory<GameHistory,String>("winner")
        );
        enemyLoser.setCellValueFactory(
                new PropertyValueFactory<GameHistory,String>("loser")
        );
        // 连接数据库
        Connection conn = null;
        Statement stmt = null;
        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(DB_URL,USER,PASS);

        stmt = conn.createStatement();
        String sql;
        //sql = "select username,user_goal,user_rank from user";
        //sql = "select * from user order by user_rank";
        sql = "select * from game_history where winner = \""+user.getUsername()+"\" or loser = \""+user.getUsername()+"\" order by end_time";
        ResultSet rs = stmt.executeQuery(sql);
        while(rs.next()){
            data.add(new GameHistory( rs.getInt(1),rs.getDate(2),rs.getString(3)
                    ,rs.getString(4),rs.getString(5)));
        }
        myHistory.setItems(data);
        System.out.println(userGameView.enemy.getUsername());
        sql = "select * from game_history where winner = \""+userGameView.enemy.getUsername()+"\" or loser = \""+userGameView.enemy.getUsername()+"\" order by end_time";
        rs = stmt.executeQuery(sql);
        while(rs.next()){
            enemyData.add(new GameHistory( rs.getInt(1),rs.getDate(2),rs.getString(3)
                    ,rs.getString(4),rs.getString(5)));
        }
        enemyHistory.setItems(enemyData);
        // 完成后关闭
        conn.close();
        stmt.close();
    }
    public void onStartButtonClicked(MouseEvent mouseEvent) throws Exception {
        // 获取当前窗口
        Stage window = (Stage) prepareButton.getScene().getWindow();
        // 监听窗口关闭
        window.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                try {
                    Connection conn = null;
                    Statement stmt = null;
                    Class.forName(JDBC_DRIVER);
                    conn = DriverManager.getConnection(DB_URL,USER,PASS);
                    stmt = conn.createStatement();
                    String sql;
                    sql = "update doublegame set userNumber = userNumber-1";
                    stmt.executeUpdate(sql);
                    // 完成后关闭
                    conn.close();
                    stmt.close();
                } catch (Exception e) {
                    e.printStackTrace();;
                }
                prepareButton.setDisable(false);
                cancelPrepareButton.setDisable(true);
            }
        });
        try {
            Connection conn = null;
            Statement stmt = null;
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            stmt = conn.createStatement();
            String sql;
            sql = "select * from doublegame";
            ResultSet rs = stmt.executeQuery(sql);
            int userNumber=0;
            while(rs.next()){
                userNumber = rs.getInt("userNumber");
            }
            // 完成后关闭
            rs.close();
            conn.close();
            stmt.close();
            if(userNumber==2){
                gameWindow.getChildren().clear();
                // 打开双人模式界面
                userGameView ugView = new userGameView(doubleGameData.dgMap,doubleGameData.dgBoundMap,gameWindow,dgCanvas);
                ugView.setUser(user);
                ugView.start(new Stage());
            }else{
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setContentText("当前准备人数为："+userNumber+",未达两人！");
                alert.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
/*        gameWindow.getChildren().clear();
        // 打开双人模式界面
        userGameView ugView = new userGameView(doubleGameData.dgMap,doubleGameData.dgBoundMap,gameWindow);
        ugView.start(new Stage());*/
    }

    public void onPrepareButtonClicked(MouseEvent mouseEvent) throws Exception {
        // 获取当前窗口
        Stage window = (Stage) prepareButton.getScene().getWindow();
        // 监听窗口关闭
        window.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                try {
                    Connection conn = null;
                    Statement stmt = null;
                    Class.forName(JDBC_DRIVER);
                    conn = DriverManager.getConnection(DB_URL,USER,PASS);
                    stmt = conn.createStatement();
                    String sql;
                    sql = "update doublegame set userNumber = userNumber-1";
                    stmt.executeUpdate(sql);
                    // 完成后关闭
                    conn.close();
                    stmt.close();
                } catch (Exception e) {
                    e.printStackTrace();;
                }
                prepareButton.setDisable(false);
                cancelPrepareButton.setDisable(true);
            }
        });
        Connection conn = null;
        Statement stmt = null;
        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(DB_URL,USER,PASS);

        stmt = conn.createStatement();
        String sql;
        sql = "update doublegame set userNumber = userNumber+1";
        stmt.executeUpdate(sql);
        // 完成后关闭
        conn.close();
        stmt.close();
        prepareButton.setDisable(true);
        cancelPrepareButton.setDisable(false);
    }
    public void onCancelPrepareButtonClicked(MouseEvent mouseEvent) throws Exception {
        // 获取当前窗口
        Stage window = (Stage) prepareButton.getScene().getWindow();
        // 监听窗口关闭
        window.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                try {
                    Connection conn = null;
                    Statement stmt = null;
                    Class.forName(JDBC_DRIVER);
                    conn = DriverManager.getConnection(DB_URL,USER,PASS);
                    stmt = conn.createStatement();
                    String sql;
                    sql = "update doublegame set userNumber = userNumber-1";
                    stmt.executeUpdate(sql);
                    // 完成后关闭
                    conn.close();
                    stmt.close();
                } catch (Exception e) {
                    e.printStackTrace();;
                }
                prepareButton.setDisable(false);
                cancelPrepareButton.setDisable(true);
            }

        });
        Connection conn = null;
        Statement stmt = null;
        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(DB_URL,USER,PASS);

        stmt = conn.createStatement();
        String sql;
        sql = "update doublegame set userNumber = userNumber-1";
        int rs = stmt.executeUpdate(sql);
        // 完成后关闭
        conn.close();
        stmt.close();
        cancelPrepareButton.setDisable(true);
        prepareButton.setDisable(false);
    }

}
